import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:old_shop/common/const/cosnt.dart';
import 'package:old_shop/common/network/network.dart';
import 'package:flutter/material.dart';
import 'package:old_shop/login&regist/view/button_view.dart';
import 'package:old_shop/login&regist/view/normal_text.dart';
import 'package:old_shop/login&regist/view/sms_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  final Map? params;

  const LoginPage({Key? key, required this.params}) : super(key: key);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  FocusNode _focusNode = FocusNode();
  TextEditingController _controller = TextEditingController();
  FocusNode _codefocusNode = FocusNode();
  TextEditingController _codeController = TextEditingController();
  String phone = "";

  @override
  void initState() {
    super.initState();
    if (widget.params != null) {
      _controller.text = widget.params!["phone"];
      phone = widget.params!["phone"];
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _codeController.dispose();
    super.dispose();
  }

  void _regist() async {
    if (_controller.text.length < 11) {
      EasyLoading.showError("请输入11位手机号码");
      return;
    }
    if (_codeController.text.isEmpty) {
      EasyLoading.showError("请输入验证码");
      return;
    }
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(seconds: 1));
    EasyLoading.dismiss();
    // 更新用户信息
    _jumpToRoot(context);
    // 注册或者登录
    // Networktool.request("login",
    //     params: {"phone": _controller.text, "phoneCode": _codeController.text},
    //     success: (data) {
    //       if (data["data"] != null) {
    //         EasyLoading.dismiss();
    //         final temp = data["data"];
    //         // 保存token
    //         SharedPreferences.getInstance().then((value) => value.setString(AppConst.KEY_user_token, temp["token"]));
    //         // 更新用户信息
    //         _jumpToRoot(context);
    //       }
    //     },
    //     fail: (msg) => EasyLoading.showError(msg));
  }

  void _jumpPwdlogin() {
    Navigator.pushNamed(context, "/pwdlogin", arguments: {"phone": _controller.text});
    // Navigator.pop(context);
  }

  void _jumpToRoot(BuildContext context) {
    SharedPreferences.getInstance().then((value) => value.setBool(AppConst.APP_IS_LOGIN, true));
    Navigator.of(context).pushNamedAndRemoveUntil('/root', (Route<dynamic> route) => false);
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _focusNode.unfocus();
          _codefocusNode.unfocus();
        },
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(15),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: size.height * 0.05,
                ),
                Text(
                  "你好，\n欢迎来到我的商城！",
                  style: AppFont.textStyle(25, color: AppColor.font333, fontWeight: FontWeight.bold),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  child: Column(
                    children: [
                      SizedBox(height: size.height * 0.1),
                      NormalTextfield(
                        hintText: "请输入手机号码",
                        backgroundColor: Colors.white,
                        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                        keyboardType: TextInputType.number,
                        focusNode: _focusNode,
                        maxLength: 11,
                        controller: _controller,
                        onSubmited: (val) {
                          setState(() {
                            phone = val;
                          });
                        },
                        onChanged: (val) {
                          print(val);
                          setState(() {
                            phone = val;
                          });
                        },
                      ),
                      SizedBox(height: 1, child: Divider()),
                      SizedBox(
                        height: 8,
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: NormalTextfield(
                              hintText: "请输入验证码",
                              backgroundColor: Colors.white,
                              maxLength: 6,
                              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                              keyboardType: TextInputType.number,
                              focusNode: _codefocusNode,
                              controller: _codeController,
                            ),
                          ),
                          SmsCounterView(
                            phone: phone,
                          )
                        ],
                      ),
                      SizedBox(height: 1, child: Divider()),
                    ],
                  ),
                ),
                BottomButton(
                  margin: const EdgeInsets.only(top: 75, left: 0, right: 0),
                  title: "登录",
                  onTap: _regist,
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: InkWell(
                    onTap: _jumpPwdlogin,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 15.0),
                      child: Text(
                        "使用账号密码登录",
                        style: AppFont.textStyle(12, color: AppColor.mainColor),
                      ),
                    ),
                  ),
                ),
                Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    InkWell(
                        onTap: () => Navigator.pushNamed(context, "/regist"),
                        child: Text(
                          "立即注册",
                          style: AppFont.textStyle(14, color: AppColor.fontgrey),
                        )),
                    Container(
                      height: 16,
                      width: 1,
                      margin: const EdgeInsets.symmetric(horizontal: 20),
                      color: AppColor.fontgrey,
                    ),
                    InkWell(
                        onTap: () => Navigator.pushNamed(context, "/forgetpwd"),
                        child: Text(
                          "忘记密码",
                          style: AppFont.textStyle(14, color: AppColor.fontgrey),
                        )),
                  ],
                ),
                SizedBox(
                  height: 8,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
